package phone.qyg.com.qyg;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.service.LocationService;

import org.xutils.view.annotation.ContentView;

import java.io.File;
import java.util.ArrayList;

import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2017/11/27 14:22
 * 邮箱：lanbuhan@163.com
 * 功能：开机广告页面
 */
@ContentView(R.layout.splash)
public class SplashActivity extends BaseActivity {

    boolean isOne = true;

    long startTime;

//       Handler handler = new Handler(){
//        public void handleMessage(android.os.Message msg) {
//
//            finish();
//        };
//    }.sendEmptyMessageDelayed(0, 3000);

    @Override
    public void initSucessView() {

        File file = new File(CommonUtil.APP_HOST_PATH_APK);
        if (!file.exists()) {
            file.mkdirs();
        }else{
            deletApkFile();
        }

        initCityData();

        AppHttpRequest.httpAppInfo(null);
    }

    private void deletApkFile() {
        String path = CommonUtil.APP_HOST_PATH_APK;
        if(isRequestStr(path)){
            CommonUtil.RecursionDeleteFile(new File(path));
        }
    }



    /**
     * 获取城市列表
     */
    private void initCityData(){

        if(!CommonUtil.isNetWork()){
            tranActivity();
            return;
        }

        startTime = System.currentTimeMillis();

        //获取当前定位 城市
        startBaiduLoca(new OnBaseLocalHostCity() {
            @Override
            public void OnBaseLocalCity(boolean isLocalHost, String city) {

                if (isLocalHost) {
                    //定位成功
                    SystemPrintl.systemPrintl("定位成功的城市---->>>" + city);
                    SharePrefUtil.saveString(SharePrefUtil.KEY.CITY,city);
                    tranActivity();
                } else {
                    //定位失败
                    SystemPrintl.systemPrintl("定位失败的城市---->>>");
                    SharePrefUtil.saveString(SharePrefUtil.KEY.CITY,ApplicationConfig.CITY);
                    tranActivity();
                }

            }

        });
    }

    /**
     *  跳转界面
     */
    private void tranActivity(){
        boolean isOneState = SharePrefUtil.getBoolean(CommonUtil.getVersion(),false);

        if(isOne){
            isOne = false;
            Class clazz = null;
            if(isOneState){
                clazz = MainActivity.class;
            }else{
                //活动默认 大图展示 grid
//                SharePrefUtil.saveString(SharePrefUtil.KEY.ACT_MODE, ApplicationConfig.RECYCLE_GIRD);
//                SharePrefUtil.saveString(SharePrefUtil.KEY.HOME_ACT_MODE, ApplicationConfig.RECYCLE_GIRD);
                //课程默认 大图展示 gird
//                SharePrefUtil.saveString(SharePrefUtil.KEY.COURSE_MODE, ApplicationConfig.RECYCLE_GIRD);
//                SharePrefUtil.saveString(SharePrefUtil.KEY.HOME_COURSE_MODE, ApplicationConfig.RECYCLE_GIRD);


//                clazz = AdvertActivity.class; //占时没有确定  隐藏
                clazz = MainActivity.class;
            }

            transController(clazz);
        }


    }

    private void transController(final Class clazz){
        if(clazz != null){

            long endTime = System.currentTimeMillis();

            final long middleTime = endTime - startTime;

            SystemPrintl.systemPrintl("我一共使用时间--->>"+middleTime);

            /*
            if(middleTime < ApplicationConfig.SPLASH_TIME){
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        long sleepTime = ApplicationConfig.SPLASH_TIME - middleTime;
                        SystemPrintl.systemPrintl("我一共睡眠时间--->>"+sleepTime);
                        try {
                            Thread.sleep(sleepTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }finally {
                            CommonUtil.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    TransformController.transformController(QXApplication.getContext(),clazz);
                                }
                            });
                        }
                    }
                }.start();
            }else{
                TransformController.transformController(QXApplication.getContext(),clazz);
            }
            */

            new Thread(){
                @Override
                public void run() {
                    super.run();
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        CommonUtil.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                SplashActivity.this.finish();
                                TransformController.transformController(QXApplication.getContext(),clazz);
                            }
                        });
                    }
                }
            }.start();



        }
    }


    @Override
    public void initData(Bundle savedInstanceState) {}

    @Override
    public void initViewHandler() {}



    /****************************百度定位权限 动态申请**************************************/
    OnBaseLocalHostCity onBaseLocalCity;
    /**
     * 开启定位功能
     */
    public void startBaiduLoca(OnBaseLocalHostCity onBaseLocalCity){

        this.onBaseLocalCity = onBaseLocalCity;
        //申请权限
        getPersimmions();

        // -----------location config ------------
        locationService = ((QXApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        //开启定位功能
        locationService.start();// 定位SDK
    }



    private LocationService locationService;//百度定位服务
    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
			/*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
//			if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//				permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
//			}
////			// 读取电话状态权限
//			if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
//				permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
//			}

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }



    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }




    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {

            locationService.stop();
            locationService.unregisterListener(mListener);
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);

                SystemPrintl.systemPrintl("定位纬度--->>>"+location.getLatitude()+",经度--->>"+location.getLongitude());
                //纬度
                SharePrefUtil.saveString(SharePrefUtil.KEY.LATITUDE,String.valueOf(location.getLatitude()));
                // 经度
                SharePrefUtil.saveString(SharePrefUtil.KEY.LONTITUDE,String.valueOf(location.getLongitude()));
                sb.append(location.getCityCode());
                sb.append("\ncity : ");// 城市
                sb.append(location.getCity());

                /*
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                */
                /**
                 * 设置回调
                 */
                if(onBaseLocalCity != null){
                    int locType = location.getLocType();
                    if(locType == BDLocation.TypeServerError || locType == BDLocation.TypeNetWorkException || locType == BDLocation.TypeCriteriaException)
                    {
                        onBaseLocalCity.OnBaseLocalCity(false,"");
                    }else{
                        String city = location.getCity();
                        onBaseLocalCity.OnBaseLocalCity(true,city);
                    }
                }
                SystemPrintl.systemPrintl(sb.toString());
            }else{
                //我在定位失败中 不知道错误是什么
                onBaseLocalCity.OnBaseLocalCity(false,"");
            }
        }

        public void onConnectHotSpotMessage(String s, int i){
        }
    };


    /**
     * 获取当前城市
     */
    public static interface OnBaseLocalHostCity{
        public void OnBaseLocalCity(boolean isLocalHost,String city);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(locationService != null){
            locationService.stop();
        }
    }


}
